package service.impl;

import dao.IUserDao;
import dao.impl.UserDaoImpl;
import entity.User;
import util.MD5Util;

import java.util.ArrayList;
import java.util.List;

public class UserServiceImpl implements service.IUserService {
    private final IUserDao userDao = new dao.impl.UserDaoImpl();
    private List<User> users;

    public UserServiceImpl() {
        users = new ArrayList<>(userDao.load());
        if (users.isEmpty()) {
            users.add(new entity.User("1001", "admin", MD5Util.encrypt("ynuinfo#777"), "管理员", "000000"));
            userDao.save(users);
        }
    }

    @Override
    public User login(String username, String password) {
        return users.stream()
                .filter(u -> u.getUsername().equals(username) && u.getPassword().equals(MD5Util.encrypt(password)))
                .findFirst()
                .orElse(null);
    }

    @Override
    public List<User> findAll() {
        return users;
    }

    @Override
    public boolean add(User user) {
        if (users.stream().anyMatch(u -> u.getUsername().equals(user.getUsername()))) return false;
        user.setId(java.util.UUID.randomUUID().toString());
        user.setPassword(MD5Util.encrypt(user.getPassword()));
        users.add(user);
        userDao.save(users);
        return true;
    }

    @Override
    public boolean delete(String id) {
        boolean result = users.removeIf(u -> u.getId().equals(id));
        if (result) {
            userDao.save(users);
        }
        return result;
    }

    @Override
    public boolean updateType(String id, String type) {
        User u = users.stream().filter(user -> user.getId().equals(id)).findFirst().orElse(null);
        if (u != null) {
            u.setType(type);
            userDao.save(users);
            return true;
        }
        return false;
    }

    @Override
    public boolean updatePhone(String id, String newPhone) {
        User u = users.stream().filter(user -> user.getId().equals(id)).findFirst().orElse(null);
        if (u != null) {
            u.setPhone(newPhone);
            userDao.save(users);
            return true;
        }
        return false;
    }

    @Override
    public void shutdown() {
        userDao.save(users);
    }
}